package org.wit.ecommerce.dao;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.wit.ecommerce.domain.ClientUser;
import org.wit.ecommerce.domain.PartnerUser;
import org.wit.ecommerce.domain.SuperUser;
import org.wit.ecommerce.domain.User;
/**
 * @spring.bean id="userDao"
 * @spring.property name="sessionFactory" ref="sessionFactoryObj"
 * @author Justin
 *
 */
public class UserDao extends SimpleHibernateDao<User, Long> {
	@SuppressWarnings("unchecked")
	public List<User> findByPage(int start, int limit, Map<String, ?> keywords) {
		String hql = "from org.wit.ecommerce.domain.User";
		Query query = createQuery(hql, keywords);
		query.setFirstResult(start);
		query.setMaxResults(limit);
		return query.list();
	}
	
	/**
	 * return total rows
	 * @author Justin
	 * @param keywords
	 * @return
	 */
	public int getTotalCount(Map<String, ?> keywords){
		String hql = "select count(*) from org.wit.ecommerce.domain.User";
		return ((Number) createQuery(hql, keywords).uniqueResult()).intValue();
	}

	/**
	 * batch delete by ids
	 * @param ids
	 */
	public void batchDelete(Long[] ids) {
		String hql = "delete from org.wit.ecommerce.domain.User where id in (" + StringUtils.join(ids,",") + ")";
		Query q = getSession().createQuery(hql);
		q.executeUpdate();
	}

	public SuperUser getSuperById(Long id) {
		String hql = "from org.wit.ecommerce.domain.SuperUser where id = ?";
		return findUnique(hql, id);
	}

	public PartnerUser getPartnerById(Long id) {
		String hql = "from org.wit.ecommerce.domain.PartnerUser where id = ?";
		return findUnique(hql, id);
	}

	public ClientUser getClientById(Long id) {
		String hql = "from org.wit.ecommerce.domain.ClientUser where id = ?";
		return findUnique(hql, id);
	}

	public User findUser(String email, String encrypt) {
		Criteria c = createCriteria(
				Restrictions.and(Restrictions.eq("email", email), Restrictions.eq("password", encrypt)));
		return (User) c.uniqueResult();
	}
}
